import { defineStore } from 'pinia'
//导入 type
import { ApiRes, CategoryItem,  TopCategoryItem,  SubCategoryItem  } from '@/types/data'
//导入 axios 
import request from '@/utils/request'
import { topCategory } from '../constants'
//将 topCategory 转为 CategoryItem 数组
let defaultCate = topCategory.map(item => {
  return {
    name: item
  }
})
const useCategoryStore = defineStore('category', {
  state: () => {
   return {
     //定义分类数据
     categoryList: defaultCate as CategoryItem[],
     topCategory: {} as TopCategoryItem,
      // 定义二级分类的数据
      subCategory: {} as SubCategoryItem
   }
  },
  actions:{
    //得到分类数据的方法
   async getAllCategory(){
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      //添加 open 控制一级分类的显示与隐藏
      res.data.result.forEach((item) => {
        item.open = false
      })
      //保存分类的数据
      this.categoryList = res.data.result
    },
    // open 来控制二级分类的显示与隐藏（定义 show & hide 方法来控制显示与隐藏）
    // 显示二类分类
    show (id: string) {
      const cateItem = this.categoryList.find(item => item.id === id)
      cateItem!.open = true
    },
    // 隐藏二级分类
    hide (id: string) {
      const cateItem = this.categoryList.find(item => item.id === id)
      cateItem!.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategoryItem>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = res.data.result
    },
     // 获取二级分类的数据
     async getSubCategory (id: string) {
      const res = await request.get<ApiRes<SubCategoryItem>>(
        '/category/sub/filter',
        {
          params: {
            id
          }
        }
      )
      this.subCategory = res.data.result
    }
  },
  getters:{}
})

export default useCategoryStore